<template>
  <div class="menu-management-tab">
    <!-- 操作栏 -->
    <el-card class="action-card">
      <div class="action-bar">
        <div class="left-actions">
          <el-button type="primary" @click="handleAddMenu">
            <el-icon><Plus /></el-icon> 添加菜单
          </el-button>
          <el-button type="success" @click="handleAddButton">
            <el-icon><Plus /></el-icon> 添加按钮
          </el-button>
        </div>
        <div class="right-actions">
          <el-button @click="refreshMenuTree">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 菜单树 -->
    <el-card class="tree-card">
      <template #header>
        <div class="card-header">
          <span>菜单结构</span>
          <el-tag type="info" size="small">
            共 {{ menuTreeData.length }} 个菜单
          </el-tag>
        </div>
      </template>

      <el-tree
        ref="menuTreeRef"
        :data="menuTreeData"
        :props="treeProps"
        :expand-on-click-node="false"
        :default-expand-all="true"
        node-key="id"
        class="menu-tree"
        draggable
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
        @node-click="handleMenuClick"
        @node-drop="handleNodeDrop"
      >
        <template #default="{ node, data }">
          <div class="menu-node" :class="{ 'dragging': node.isDragging }">
            <div class="node-content">
              <el-icon v-if="data.icon" :size="16" class="node-icon">
                <component :is="getIconComponent(data.icon)" />
              </el-icon>
              <span class="node-label">{{ data.name }}</span>
              <el-tag :type="data.type === 'MENU' ? 'primary' : 'success'" size="small" class="type-tag">
                {{ data.type === 'MENU' ? '菜单' : '按钮' }}
              </el-tag>
              <el-tag v-if="data.path" type="info" size="small" class="path-tag">
                {{ data.path }}
              </el-tag>
              <el-tag v-if="data.order !== undefined" type="warning" size="small" class="order-tag">
                排序: {{ data.order }}
              </el-tag>
            </div>
            <div class="node-actions">
              <el-button 
                v-if="data.type === 'MENU'"
                type="success" 
                size="small" 
                @click.stop="handleAddButtonToMenu(data)"
              >
                添加按钮
              </el-button>
              <el-button type="primary" size="small" @click.stop="handleEditMenu(data)">
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click.stop="data.type === 'MENU' ? handleDeleteMenu(data) : handleDeleteButton(data)"
                :disabled="data.roles && data.roles.length > 0"
              >
                删除
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>

    <!-- 按钮权限列表 -->
    <el-card v-if="selectedMenu" class="button-card">
      <template #header>
        <div class="card-header">
          <span>{{ selectedMenu.name }} - 按钮权限</span>
          <el-button type="success" size="small" @click="handleAddButtonToMenu(selectedMenu)">
            添加按钮
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="buttonLoading"
        :data="buttonList"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="按钮名称" min-width="120" />
        <el-table-column prop="code" label="按钮代码" min-width="150" />
        <el-table-column prop="method" label="HTTP方法" width="100">
          <template #default="{ row }">
            <el-tag :type="getMethodTagType(row.method)" size="small">
              {{ row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="order" label="排序" width="80" />
        <el-table-column prop="enable" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.enable ? 'success' : 'danger'" size="small">
              {{ row.enable ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditButton(row)">编辑</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteButton(row)"
              :disabled="row.roles && row.roles.length > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限编辑对话框 -->
    <PermissionEditDialog 
      v-model="dialogVisible"
      :permission="currentPermission"
      :is-edit="isEdit"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { 
  Plus,
  Refresh
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import { permissionApi, Permission, METHOD_TYPE_OPTIONS } from '../api/permission'
import { getIconComponent } from '../utils/iconUtils'
import PermissionEditDialog from './PermissionEditDialog.vue'

// 树组件引用
const menuTreeRef = ref<InstanceType<typeof ElTree> | null>(null)

// 加载状态
const loading = ref(false)
const buttonLoading = ref(false)

// 菜单树数据
const menuTreeData = ref<Permission[]>([])

// 选中的菜单
const selectedMenu = ref<Permission | null>(null)

// 按钮列表
const buttonList = ref<Permission[]>([])

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentPermission = ref<Permission | null>(null)

// 树组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 获取菜单树
const fetchMenuTree = async () => {
  loading.value = true
  try {
    const res = await permissionApi.getMenuTree()
    
    if (res && res.code === 200) {
      menuTreeData.value = res.data || []
    } else {
      ElMessage.error('获取菜单树失败')
    }
  } catch (error) {
    ElMessage.error('获取菜单树失败')
  } finally {
    loading.value = false
  }
}

// 获取按钮权限
const fetchButtonPermissions = async (parentId: number) => {
  buttonLoading.value = true
  try {
    const res = await permissionApi.getButtonPermissions(parentId)
    
    if (res && res.code === 200) {
      buttonList.value = res.data || []
    } else {
      ElMessage.error('获取按钮权限失败')
    }
  } catch (error) {
    ElMessage.error('获取按钮权限失败')
  } finally {
    buttonLoading.value = false
  }
}

// 刷新菜单树
const refreshMenuTree = () => {
  fetchMenuTree()
  selectedMenu.value = null
  buttonList.value = []
}

// 添加菜单
const handleAddMenu = () => {
  isEdit.value = false
  currentPermission.value = {
    type: 'MENU'
  } as Permission
  dialogVisible.value = true
}

// 添加按钮
const handleAddButton = () => {
  isEdit.value = false
  currentPermission.value = {
    type: 'BUTTON'
  } as Permission
  dialogVisible.value = true
}

// 为菜单添加按钮
const handleAddButtonToMenu = (menu: Permission) => {
  isEdit.value = false
  currentPermission.value = {
    type: 'BUTTON',
    parentId: menu.id
  } as Permission
  dialogVisible.value = true
}

// 编辑菜单
const handleEditMenu = (menu: Permission) => {
  isEdit.value = true
  currentPermission.value = { ...menu }
  dialogVisible.value = true
}

// 删除菜单
const handleDeleteMenu = (menu: Permission) => {
  if (menu.roles && menu.roles.length > 0) {
    ElMessage.warning('该菜单已被角色使用，无法删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除菜单 "${menu.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await permissionApi.deletePermission(menu.id)
      
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        fetchMenuTree()
        if (selectedMenu.value && selectedMenu.value.id === menu.id) {
          selectedMenu.value = null
          buttonList.value = []
        }
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 编辑按钮
const handleEditButton = (button: Permission) => {
  isEdit.value = true
  currentPermission.value = { ...button }
  dialogVisible.value = true
}

// 删除按钮
const handleDeleteButton = (button: Permission) => {
  if (button.roles && button.roles.length > 0) {
    ElMessage.warning('该按钮已被角色使用，无法删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除按钮 "${button.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await permissionApi.deletePermission(button.id)
      
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        if (selectedMenu.value) {
          fetchButtonPermissions(selectedMenu.value.id)
        }
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 菜单点击
const handleMenuClick = (data: Permission) => {
  selectedMenu.value = data
  fetchButtonPermissions(data.id)
}

// 对话框成功回调
const handleDialogSuccess = () => {
  dialogVisible.value = false
  fetchMenuTree()
  if (selectedMenu.value) {
    fetchButtonPermissions(selectedMenu.value.id)
  }
}

// 获取方法标签类型
const getMethodTagType = (method: string): string => {
  const methodMap: Record<string, string> = {
    'GET': 'success',
    'POST': 'primary',
    'PATCH': 'warning',
    'DELETE': 'danger'
  }
  return methodMap[method] || 'info'
}

// 拖动相关处理
const allowDrag = (node: any) => {
  return true // 允许所有节点拖动
}

const allowDrop = (draggingNode: any, dropNode: any, type: string) => {
  // 不允许拖拽到按钮类型的节点下
  if (dropNode.data.type === 'BUTTON') {
    return false
  }
  
  // 按钮类型的节点只能拖拽到菜单类型的节点下
  if (draggingNode.data.type === 'BUTTON' && dropNode.data.type !== 'MENU') {
    return false
  }
  
  return true
}

// 处理节点拖拽完成
const handleNodeDrop = async (draggingNode: any, dropNode: any, dropType: string, ev: any) => {
  try {
    const draggingData = draggingNode.data
    let newParentId = null
    let newOrder = 0
    
    if (dropType === 'inner') {
      // 拖拽到节点内部
      newParentId = dropNode.data.id
      newOrder = dropNode.data.children ? dropNode.data.children.length : 0
    } else if (dropType === 'prev' || dropType === 'next') {
      // 拖拽到节点前面或后面
      newParentId = dropNode.data.parentId
      const siblings = dropNode.parent?.data?.children || menuTreeData.value
      const dropIndex = siblings.findIndex((item: any) => item.id === dropNode.data.id)
      newOrder = dropType === 'prev' ? dropIndex : dropIndex + 1
    }
    
    // 更新权限的父级和排序
    const updateData = {
      parentId: newParentId,
      order: newOrder
    }
    
    const res = await permissionApi.updatePermission(draggingData.id, updateData)
    
    if (res && res.code === 200) {
      ElMessage.success('菜单顺序更新成功')
      // 刷新菜单树
      await fetchMenuTree()
    } else {
      ElMessage.error('更新菜单顺序失败')
      // 刷新菜单树以恢复原状态
      await fetchMenuTree()
    }
  } catch (error) {
    console.error('更新菜单顺序失败:', error)
    ElMessage.error('更新菜单顺序失败')
    // 刷新菜单树以恢复原状态
    await fetchMenuTree()
  }
}

// 加载数据
onMounted(() => {
  fetchMenuTree()
})
</script>

<style scoped>
.menu-management-tab {
  padding: 0;
}

.action-card {
  margin-bottom: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 8px;
}

.tree-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.menu-tree {
  min-height: 300px;
}

.menu-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 20px;
  cursor: move;
  transition: all 0.2s ease;
}

.menu-node:hover {
  background-color: var(--el-color-primary-light-9);
  border-radius: 4px;
}

.menu-node.dragging {
  opacity: 0.6;
  transform: scale(0.95);
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-icon {
  color: var(--el-color-primary);
}

.node-label {
  font-weight: 500;
}

.type-tag,
.path-tag,
.order-tag {
  margin-left: 4px;
}

.node-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.menu-node:hover .node-actions {
  opacity: 1;
}

.button-card {
  margin-bottom: 20px;
}

/* 树节点内容样式 */
:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
  display: flex;
  align-items: center;
}

/* 展开图标样式 */
:deep(.el-tree-node__expand-icon) {
  margin-right: 8px;
}

/* 重置所有可能影响缩进的样式 */
:deep(.el-tree-node) {
  margin-left: 0 !important;
  padding-left: 0 !important;
}

:deep(.el-tree-node__content-wrapper) {
  margin-left: 0 !important;
  padding-left: 0 !important;
}

/* 使用Element Plus默认的缩进机制 */
:deep(.el-tree-node__children) {
  margin-left: 0 !important;
  padding-left: 0 !important;
}

/* 确保树组件使用默认缩进 */
:deep(.el-tree) {
  --el-tree-node-indent: 18px;
}

/* 修复拖拽时的样式 */
:deep(.el-tree-node.is-drop-inner) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-tree-node.is-drop-inner .el-tree-node__content) {
  background-color: var(--el-color-primary-light-9);
}

/* 拖拽时的占位线样式 */
:deep(.el-tree-node__placeholder) {
  background-color: var(--el-color-primary);
  height: 2px;
  margin: 2px 0;
  border-radius: 1px;
}
</style>
